package org.jash.ting13.home

import androidx.paging.PagingSource
import androidx.paging.PagingState
import org.jash.ting13.entity.SearchEntity
import org.jash.ting13.net.APIService
import org.jash.utils.log

class SearchPagingSource(val service:APIService, val keyword:String): PagingSource<Int, SearchEntity>() {
    override fun getRefreshKey(state: PagingState<Int, SearchEntity>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, SearchEntity> {
        try {
            // Start refresh at page 1 if undefined.
            val nextPageNumber = params.key ?: 1
            val response = service.search(keyword, nextPageNumber)
            return LoadResult.Page(
                data = response.entities,
                prevKey = null, // Only paging forward.
                nextKey = if (nextPageNumber < (response.totalPage ?: 0)) nextPageNumber + 1 else null
            )
        } catch (e: Exception) {
            return LoadResult.Error(e)
        }
    }
}